from flask import Blueprint, request

from controllers import R
from mauth import HasPerm
from models.user import User
from services import LowCodeServiceUtil
from services.user_service import UserService
from validators import BasePageForm
from validators.id_validator import IdForm, IdsForm
from validators.user_validator import UserForm

# 声明一个蓝图
user = Blueprint("user", __name__, url_prefix="/sys/user")

# 声明一个用户业务服务
user_service = UserService(model=User)


@user.route("/detail", methods=["POST"])
@HasPerm(access="sys:user:detail", name="通过id获取用户信息")
def user_detail():
    """
    通过id获取用户信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = User.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = user_service.detail(form)
    if u is not None:
        return R.data(u.to_dict())
    else:
        return R.fail("该记录不存在")


@user.route("/page", methods=["POST"])
@HasPerm(access="sys:user:page", name="分页查询用户列表")
def user_page():
    """
    分页查询用户列表
    ---
    tags:
        - 用户
    security:
        - Auth:[]
    parameters:
        -  in: header
           name: Authorization
           type: string
           required: true
           description: Bearer token for authentication.
    responses:
          200:
            description: 成功
            schema:
              type: object
              properties:
                code:
                  type: integer
                  description: 响应状态码，0 表示成功
                data:
                  type: object
                  properties:
                    pageNum:
                      type: integer
                      description: 当前页码
                    pageSize:
                      type: integer
                      description: 每页记录数
                    recordCount:
                      type: integer
                      description: 总记录数
                    rows:
                      type: array
                      items:
                        type: object
                        properties:
                          adminType:
                            type: integer
                            description: 管理员类型
                          createTime:
                            type: string
                            description: 创建时间
                          createUser:
                            type: string
                            description: 创建用户 ID
                          deptId:
                            type: string
                            description: 部门 ID
                          id:
                            type: string
                            description: 用户 ID
                          isDeleted:
                            type: boolean
                            description: 是否删除
                          isLocked:
                            type: integer
                            description: 是否锁定
                          mobilePhone:
                            type: string
                            description: 手机号码
                          password:
                            type: string
                            description: 用户密码
                          postId:
                            type: string
                            description: 岗位 ID
                          realName:
                            type: string
                            description: 用户真实姓名
                          roleIds:
                            type: string
                            description: 角色 ID
                          salt:
                            type: string
                            description: 加密盐
                          sex:
                            type: integer
                            description: 用户性别
                          updateTime:
                            type: string
                            description: 更新时间
                          updateUser:
                            type: string
                            description: 更新用户 ID
                          userName:
                            type: string
                            description: 用户名
                          nickName:
                            type: string
                            description: 用户昵称，可能为空
                    totalPage:
                      type: integer
                      description: 总页数
                msg:
                  type: string
                  description: 响应消息
    """
    form = BasePageForm()
    form.validate_for_api()
    return R.data(user_service.page(form))


@user.route("/save", methods=["POST"])
@HasPerm(access="sys:user:save", name="添加用户")
def user_save():
    """
    添加用户
    :return:
    """
    form = UserForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    user_service.save(form)
    return R.success("添加用户成功")


@user.route("/update", methods=["POST"])
@HasPerm(access="sys:user:update", name="修改用户")
def user_update():
    """
    修改用户
    :return:
    """
    form = UserForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    user_service.update(form)
    return R.success("修改用户成功")


@user.route("/remove", methods=["POST"])
@HasPerm(access="sys:user:remove", name="删除用户")
def user_remove():
    """
    删除用户
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    user_service.remove(form)
    return R.success("删除用户成功")


@user.route("/permCode", methods=["POST"])
@HasPerm(name="获取当前登录用户权限码")
def perm_code():
    """
    获取当前登录用户权限码
    """
    return R.data(user_service.perm_code())


@user.route("/info", methods=["POST"])
@HasPerm(name="获取当前登录用户信息")
def user_info():
    """
    获取当前登录用户信息
    :return:
    """
    return R.data(user_service.info())


@user.route("/select", methods=["POST"])
@HasPerm(name="下拉用户")
def user_select():
    """
    下拉用户
    :return:
    """
    return R.data(
        LowCodeServiceUtil.select(
            moduleName="sys", tableName="user", labelKey="realName", valueKey="id"
        )
    )


@user.route("/updatePwd", methods=["POST"])
@HasPerm(name="修改用户个人密码")
def user_update_pwd():
    """
    修改用户个人密码
    :return:
    """
    user_service.update_pwd(request.json)
    return R.success()


@user.route("/resetPassword", methods=["POST"])
@HasPerm(access="sys:user:resetPassword", name="重置用户密码")
def reset_pwd():
    """
    重置用户密码
    """
    form = IdsForm()
    form.validate_for_api()
    user_service.reset_pwd(form.ids.data)
    return R.success()


@user.route("/locked", methods=["POST"])
@HasPerm(access="sys:user:locked,sys:user:unLocked", name="锁定用户")
def locked():
    """
    锁定用户
    """
    form = IdsForm()
    form.validate_for_api()
    user_service.locked(form.ids.data)
    return R.success()


@user.route("/unLocked", methods=["POST"])
@HasPerm(access="sys:user:locked,sys:user:unLocked", name="取消锁定用户")
def un_locked():
    """
    取消锁定用户
    """
    form = IdsForm()
    form.validate_for_api()
    user_service.un_locked(form.ids.data)
    return R.success()


@user.route("/getDeptUserTree", methods=["POST"])
@HasPerm(name="获取部门用户树")
def get_dept_user_tree():
    """
    获取部门用户树
    """
    return R.data(user_service.get_dept_user_tree())


@user.route("/grantRole", methods=["POST"])
@HasPerm(access="sys:user:grantRole", name="给用户授权角色")
def grant_role():
    """
    给用户授权角色
    """
    form = request.json
    userId = form.get("userId")
    roleIds = form.get("roleIdList")
    user_service.grant_role(userId, roleIds)
    return R.success()


@user.route("/onlineUserList", methods=["POST"])
@HasPerm(access="sys:user:onlineUserList", name="获取在线用户列表")
def online_user_list():
    """
    获取在线用户列表
    """
    keywords = request.json.get("keywords")
    return R.data(user_service.online_user_list(keywords=keywords))


@user.route("/logoutByTokenValue", methods=["POST"])
@HasPerm(access="sys:user:logoutByTokenValue", name="根据token值强制注销")
def logout_by_token_value():
    """
    根据token值强制注销
    """
    user_service.logout_by_token_value(request.json.get("ids"))
    return R.success()


@user.route("/kickoutByTokenValue", methods=["POST"])
@HasPerm(access="sys:user:kickoutByTokenValue", name="根据token值踢下线")
def kickout_by_token_value():
    """
    根据token值踢下线
    """
    user_service.kickout_by_token_value(request.json.get("ids"))
    return R.success()


@user.route("/logoutByLoginId", methods=["POST"])
@HasPerm(access="sys:user:logoutByLoginId", name="根据登录ID强制注销")
def logout_by_login_id():
    """
    根据登录ID强制注销
    """
    user_service.logout_by_login_id(request.json.get("ids"))
    return R.success()


@user.route("/kickoutByLoginId", methods=["POST"])
@HasPerm(access="sys:user:kickoutByLoginId", name="根据登录ID踢下线")
def kickout_by_login_id():
    """
    根据登录ID踢下线
    """
    user_service.kickout_by_login_id(request.json.get("ids"))
    return R.success()
